from bokeh.plotting import figure, show
from bokeh.models import ColumnDataSource, HoverTool
import json
import sys

# 检查是否传入了文件名作为参数
if len(sys.argv) < 2:
    print("请提供JSON文件的路径作为参数.")
    sys.exit(1)

# 从命令行获取文件名
file_name = sys.argv[1]

# 从文件中读取JSON数据
with open(file_name, 'r') as f:
    data = json.load(f)

# 提取points和polygons信息
points = data['navmesh']['points']
polygons = data['navmesh']['merged_polygon_indexs']

# 提取坐标
x_coords = [p['x'] for p in points]
y_coords = [p['y'] for p in points]

# 准备多边形数据
polygons_data = {
    'xs': [],  # 每个多边形的x坐标列表
    'ys': [],  # 每个多边形的y坐标列表
    'colors': []  # 每个多边形的颜色
}

# 定义颜色
colors = ['green', 'red']

# 遍历多边形组
for group_idx, group in enumerate(polygons):
    for i, polygon in enumerate(group):
        polygon_x = [x_coords[j] for j in polygon] + [x_coords[polygon[0]]]  # 闭合多边形
        polygon_y = [y_coords[j] for j in polygon] + [y_coords[polygon[0]]]
        polygons_data['xs'].append(polygon_x)
        polygons_data['ys'].append(polygon_y)
        polygons_data['colors'].append('green' if i == 0 else 'red')

# 创建数据源
source = ColumnDataSource(data=polygons_data)

# 创建绘图对象
p = figure(title="Navmesh Polygons with Mouse Tracking", tools="pan,box_zoom,reset,hover", match_aspect=True)
p.xaxis.axis_label = "X Axis"
p.yaxis.axis_label = "Y Axis"

# 绘制多边形
p.patches(xs='xs', ys='ys', fill_color='colors', line_color="black", source=source)

# 添加鼠标悬停工具，动态显示鼠标位置
hover = HoverTool(tooltips=[
    ("Mouse Position (Formatted)", "($x{0.00}, $y{0.00})")  # 显示格式化鼠标位置
])
p.add_tools(hover)

# 显示图形
show(p)
